package com.system.service;

import com.system.controller.CommentController;
import com.system.controller.ReplyCommentController;
import com.system.menu.UI;
import com.system.untils.SensitiveWordsInspect;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.InputMismatchException;
import java.util.Map;
import java.util.Scanner;

public class ReplyComment {
    private final Scanner sc;
    private final ReplyCommentController controller;
    private final UI ui = new UI();
    private final SensitiveWordsInspect swi = new SensitiveWordsInspect();
    private final CommentController commentController;
    public ReplyComment() {

        this.controller = new ReplyCommentController();
        this.commentController = new CommentController();
        this.sc = new Scanner(System.in);
    }

    public void replyCommentMenu(String email,int commentID,int publishID) {
            while (true) {
                this.ui.HeadLine();
                this.commentController.getCdm().show(publishID);
                // 评论
                this.controller.getRcm().selectAllChildComment(commentID);
                this.ui.replayCommentUI();
                System.out.println("请选择：");
                int optionComment = sc.nextInt();
                try {
                    switch (optionComment) {
                        case 1:
                            // 1.回复评论
                            replyComment(email, commentID);
                            break;
                        case 2:
                            //2.输入回复评论序号
                            inputReplyComment(email, commentID);
                            break;
                        case 3:
                            //3.查看更多评论
                            selectAllComments(email, commentID, publishID);
                            break;
                        case 4:
                            //4.刷新
                            replyCommentMenu(email, commentID, publishID);
                            return;
                        case 5:
                            return;
                        default:
                            System.out.println("输入错误!");
                            break;
                    }
                }catch(InputMismatchException e) {
                    System.out.println("输入错误，请输入数字！");
                    sc.next(); // 清除错误输入
                }
            }
    }

    public void replyComment(String email,int commentID) {
        boolean flag = true;
        while (flag) {
            sc.nextLine();
            System.out.println("请输入回复内容(连续回车继续输入，输入END结束):");
            String replyText = multiLineInput();
            if (!(this.swi.inspectText(replyText))) {
                // 插入
                if (this.controller.getRcm().addReplyComment(commentID,email,replyText)) {
                    flag = false;
                }else
                {
                    System.out.println("添加失败！");
                }
            }else {
                System.out.println("输入含有敏感词汇!");
                replyComment(email,commentID);
            }
        }
    }


    public int getTotalPages(int id) {
        int totalRecords = this.controller.getRcm().countParentAmounts(id);  // 获取总记录数
        int pageSize = 5; // 每页显示5条
        return (int) Math.ceil((double) totalRecords / pageSize); // 向上取整得到总页数
    }

    public void inputReplyComment(String email, int commentID) {
        while (true) {
            try {
                // 提示用户输入回复评论的序号
                System.out.println("请输入回复评论的序号：");
                int inputID = sc.nextInt();
                sc.nextLine(); // 消耗掉整数输入后的换行符

                // 获取回复映射
                Map<Integer, Integer> replyMap = this.controller.getRcm().lockReplyID(commentID);
                Integer replyID = replyMap.get(inputID);

                // 检查回复评论是否存在
                if (replyID != null) {
                    System.out.println("请输入回复的信息（连续回车继续输入，输入END结束）：");

                    // 调用多行输入方法获取完整的回复内容
                    String replyText = multiLineInput();

                    // 检查敏感词汇并尝试添加评论
                    if (isValidReply(replyText, replyID, email)) {
                        System.out.println("回复成功！");
                        return; // 成功后退出循环
                    } else {
                        System.out.println("输入含有敏感词汇!");
                    }
                } else {
                    System.out.println("评论不存在，请重新输入序号！");
                }
            } catch (InputMismatchException e) {
                System.out.println("输入错误，请输入数字！");
                sc.next(); // 清除错误输入
            }
        }
    }

    private String multiLineInput() {
        StringBuilder inputBuilder = new StringBuilder();
        while (true) {
            String line = sc.nextLine();
            if ("END".equalsIgnoreCase(line.trim())) { // 判断是否结束输入
                break;
            }
            inputBuilder.append(line).append(System.lineSeparator());
        }
        return inputBuilder.toString().trim(); // 去除多余的换行符
    }

    private boolean isValidReply(String replyText, int replyID, String email) {
        // 检查敏感词汇并尝试添加评论
        return !this.swi.inspectText(replyText) &&
                this.controller.getRcm().addReplyComment(replyID, email, replyText);
    }

    public void selectAllComments(String email,int commentID, int publishID) {
        if (this.controller.getRcm().countParentAmounts(commentID) == 0) {
            System.out.println("该评论下没有更多的评论！");
            return;
        }
        int currentPage = 1;
        int totalPages = getTotalPages(commentID);
        printPageInfo(currentPage, totalPages);
        showComments(currentPage, commentID, publishID); // 初始显示评论
        while (true) {
            this.ui.replyCommentUI(); // 显示评论界面
            System.out.println("请输入你的选择：");
            try {
                int optAllTopics = sc.nextInt();
                switch (optAllTopics) {
                    case 1:
                        // 回复帖子
                        inputReplyComment(email,commentID);
                        break;
                    case 2:
                        // 查看下一页
                        if (currentPage < totalPages) {
                            currentPage++;
                            showComments(currentPage, commentID, publishID);
                        } else {
                            System.out.println("已经是最后一页！");
                        }
                        break;
                    case 3:
                        // 查看上一页
                        if (currentPage > 1) {
                            currentPage--;
                            showComments(currentPage, commentID, publishID);
                        } else {
                            System.out.println("已经是第一页！");
                        }
                        break;
                    case 4:
                        return;
                    default:
                        System.out.println("输入有误，请重新选择！");
                        break;
                }
            } catch (InputMismatchException e) {
                System.out.println("输入错误，请输入数字！");
                sc.next(); // 清除错误输入
            }
        }
    }
    private void printPageInfo(int currentPage, int totalPages) {
        System.out.println("\t\t\t\t\t\t\t当前页：" + currentPage + "  共 " + totalPages + " 页");
    }
    private void showComments(int currentPage, int commentID, int publishID) {
        this.commentController.getCdm().show(publishID);
        this.controller.getRcm().searchAllCurrentID(currentPage, commentID);
        printPageInfo(currentPage, getTotalPages(commentID)); // 每次显示评论时更新页码信息
    }
}